<template>
  <page-layout>
    <a-card>
      <a-button size="large" @click="$router.go(-1)">返回</a-button>
      <a-form
        style="margin-top: 36px"
        :form="form"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-item label="用户名" required>
          <a-input
            placeholder="请输入用户名"
            size="large"
            v-decorator="[
              'username',
              {
                initialValue: editData.username,
                rules: [{ required: true, message: '请输入用户名!' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item label="用户昵称" required>
          <a-input
            placeholder="请输入用户昵称"
            size="large"
            v-decorator="[
              'name',
              {
                initialValue: editData.name,
                rules: [{ required: true, message: '请输入用户昵称!' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item label="邮箱" >
          <a-input
            placeholder="请输入邮箱"
            size="large"
            v-decorator="[
              'email',
              {
                initialValue: editData.email,
                rules: [{ required: false, message: '请输入邮箱!' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <!-- {{ selectDatas[0] }} -->
        <a-form-item label="角色">
          <a-select
            placeholder="请选择角色"
            size="large"
            mode="multiple"
            v-decorator="[
              'roles',
              {
                initialValue: editData.all_roles,
                rules: [{ required: true, message: '请选择角色!'}]
              }
            ]"
            @change="handleSelectChange"
          >
            <a-select-option
              v-for="item in selectDatas[0]"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="部门">
          <a-select
            placeholder="请选择部门"
            size="large"
            v-decorator="[
              'department_id',
              {
                initialValue: editData.department_id,
                rules: [{ required: true, message: '请选择部门!' }]
              }
            ]"
            @change="handleSelectChange"
          >
            <a-select-option
              v-for="item in selectDatas[1]"
              :key="item.department_id"
              :value="item.department_id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="密码" required>
          <a-input
            placeholder="请输入密码"
            size="large"
            type="password"
            v-decorator="[
              'password',
              {
                initialValue: editData.password,
                rules: [{ required: true, message: '请输入密码!' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item label="确认密码" required>
          <a-input
            type="password"
            placeholder="请输入确认密码"
            size="large"
            v-decorator="[
              'password_confirmation',
              {
                initialValue: editData.password,
                rules: [{ required: true, message: '请输入确认密码!' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 10 }">
          <a-button type="primary" size="large" @click="handleSubmit">
            提交
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </page-layout>
</template>

<script>
import { add, detail, edit } from "@/services/user";
import { getRoles } from "@/services/roles";
import { getDepartments } from "@/services/department";
import PageLayout from "@/layouts/PageLayout";
export default {
  name: "demand",
  components: { PageLayout },
  data() {
    this.form = this.$form.createForm(this);
    return {
      isClear: false,
      selectDatas: [],
      editData: {}
    };
  },
  created() {
    // 如果时编辑过来
    if (this.$route.query.id) {
      Promise.all([
        detail(this.$route.query.id),
        getRoles({ type: 2 }),
        getDepartments({ type: 2 })
      ]).then((arr) => {
        console.log(arr, "arr1");
        const editData = arr.splice(0, 1);
        let {
          id,
          username,
          name,
          email,
          all_roles,
          password,
          department_id
        } = editData[0].data.data;
        // 暂存角色key的数组
        let keyArr = [];
        // 循环请求到的用户的选择的角色列表
        for (let key in all_roles) {
          // 把角色的key存到暂存的数组中
          keyArr.push(Number(key));
        }
        // 把暂存的赋值给变量
        all_roles = keyArr;
        // console.log(keyArr);
        this.editData = {
          id,
          username,
          name,
          email,
          all_roles,
          password,
          department_id
        };
        // console.log(editData, "editData");
        this.selectDatas = arr.map((item) => {
          // console.log(index, item);

          // if (index === 1) return item.data.data.data;
          return item.data.data;
        });
        console.log(this.selectDatas);
      });
    } else {
      Promise.all([getRoles({ type: 2 }), getDepartments({ type: 2 })]).then(
        (arr) => {
          // console.log(arr, "arr");
          this.selectDatas = arr.map((item) => {
            // if (index === 1) return item.data.data.data;
            return item.data.data;
          });
        }
      );
    }
  },

  computed: {},
  methods: {
    handleSelectChange() {},
    handleSubmit() {
      this.form.validateFields((err, values) => {
        console.log(err, values);
        if (!err) {
          if (!this.$route.query.id) {
            add(values).then((res) => {
              // console.log(res, res);
              if (res.data.code === 20000) {
                this.$message.success({
                  content: res.data.message || "提交成功~",
                  onClose: () => {
                    this.form.resetFields();
                    this.$router.go(-1);
                  }
                });
              }
            });
          } else {
            edit({ ...this.editData, ...values }).then((res) => {
              // console.log(res, res);
              if (res.data.code === 20000) {
                this.$message.success({
                  content: res.data.message || "修改成功~",
                  onClose: () => {
                    this.form.resetFields();
                    this.$router.go(-1);
                  }
                });
              }
            });
          }
        }
      });
    },
    handleChange(info) {
      const status = info.file.status;
      if (status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      if (status === "done") {
        this.$message.success(`${info.file.name} 上传成功~`);
      } else if (status === "error") {
        this.$message.error(`${info.file.name} file upload failed.`);
      }
    },
    beforeUpload(file, fileList) {
      console.log(111);
      console.log(file, fileList);

      console.log(this.form.getFieldValue("dragger"), 111);
      if (fileList.length > 1) {
        this.$message.error("头像只能上传一张哦~");
        return false;
      }
    },
    normFile(e) {
      console.log("Upload event:", e);
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    }
  }
};
</script>

<style lang="less" scoped>
</style>
